"""
导入服务：使用策略将外部文件写入数据库
"""
from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Type

from sqlalchemy.orm import Session

from ..repository import ProjectRepository
from ..enums import IOFormat
from ..strategies.base import ImportStrategy
from ..strategies.json_strategy import JsonImportStrategy
from ..strategies.excel_strategy import ExcelImportStrategy


class UnknownImportFormatError(RuntimeError):
    """不支持的导入格式"""


IMPORT_STRATEGIES: Dict[IOFormat, Type[ImportStrategy]] = {
    IOFormat.JSON: JsonImportStrategy,
    IOFormat.EXCEL: ExcelImportStrategy,
}


@dataclass
class ImportResponse:
    project_id: int
    project_name: str
    project_name_en: str
    categories: int
    parameters: int
    values: int


class ProjectImporter:
    """导入器"""

    def __init__(self, db: Session):
        self.repository = ProjectRepository(db)

    def import_file(self, input_path: Path, format_: IOFormat) -> ImportResponse:
        strategy_cls = IMPORT_STRATEGIES.get(format_)
        if not strategy_cls:
            raise UnknownImportFormatError(f"不支持的导入格式: {format_.value}")
        strategy = strategy_cls()
        snapshot = strategy.import_snapshot(input_path)
        persist_result = self.repository.persist_snapshot(snapshot)
        project = persist_result.project
        return ImportResponse(
            project_id=project.id,
            project_name=project.name,
            project_name_en=project.name_en,
            categories=persist_result.created_categories,
            parameters=persist_result.created_parameters,
            values=persist_result.created_values,
        )

